package cn.jd.test;

import cn.jd.utils.ESClientUtil;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.Test;

public class Complicated {
    @Test
    public void testCom(){
        // 获取连接
        TransportClient client = ESClientUtil.getClient();
        //获取对象
        SearchRequestBuilder builder = client.prepareSearch("pethome");
        // 类型
        builder.setTypes("employee");
        // 搜索对象
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 指定查询
        boolQuery.must(QueryBuilders.matchQuery("name", "王天霸"));
        // 过滤
        boolQuery.filter(QueryBuilders.rangeQuery("age").gte(1).lte(12)).filter(QueryBuilders.termQuery("sex", true));
        // 将搜索条件放到收缩对象中
        builder.setQuery(boolQuery);
        // 查询的起始页
        builder.setFrom(0);
        // 条数
        builder.setSize(6);
        // 设置排序
        builder.addSort("age", SortOrder.DESC);
        // 获取结果
        SearchHits hits = builder.get().getHits();
        for (SearchHit hit : hits) {
            System.out.println(hit.getSourceAsMap());
        }
    }
    @Test
    public void test(){
        // 获取连接
        TransportClient client = ESClientUtil.getClient();
        // 获取连接对象
        SearchRequestBuilder builder = client.prepareSearch("pethome");
        // 指定类型
        builder.setTypes("employee");
        // 搜索对象
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 查询的内容
        boolQuery.must(QueryBuilders.matchQuery("name", "阮经天"));
        // 过滤
        boolQuery.filter(QueryBuilders.rangeQuery("age").gte(1).lte(12)).filter(QueryBuilders.termQuery("sex", false));
        // 将搜索条件放到收缩对象中
        builder.setQuery(boolQuery);
        //每页多少条
        builder.setSize(2);
        // 第几页开始
        builder.setFrom(0);
        // 根据年龄排序
        builder.addSort("age",SortOrder.DESC);
        // 结果
        SearchHits hits = builder.get().getHits();
        for (SearchHit hit : hits) {
            System.out.println(hit.getSourceAsMap());
        }
    }
}
